'use strict';

const Service = require('egg').Service;
const uuidv4 = require('uuid').v4
// 先阶段，已完成任务
class CategoryService extends Service {
  // 查询全部的章节
  async getAllCategories(bid){
    let res = {}
    let result = await this.app.mysql.select('category',{
      where:{bid:bid},
      columns:['id','title','content','seq'],
      orders:[['seq','asc']]
    })
    if(result){
      res.code = 0
      res.msg = '获取章节成功'
      res.data = result
    }else{
      res.code = -1
      res.msg = '获取章节失败'
    }
    return res
  }
  async getAllCategoryTitle(bid){
    let res = {}
    let result = await this.app.mysql.select('category',{
      where:{bid:bid},
      columns:['id','title'],
      orders:[['seq','asc']]
    })
    if(result){
      res.code = 0
      res.msg = '获取章节成功'
      res.data = result
    }else{
      res.code = -1
      res.msg = '获取章节失败'
    }
    return res
  }

  async getAllCategoriesWidthContent(bid){
    let res = {}
    let result = await this.app.mysql.select('category',{
      where:{bid:bid},
      columns:['id','title','content'],
      orders:[['seq','asc']]
    })
    if(result){
      res.code = 0
      res.msg = '获取章节成功'
      res.data = result
    }else{
      res.code = -1
      res.msg = '获取章节失败'
    }
    return res
  }

  // 查询指定章节
  async getAllCategoryById(bid,cid){
    let res = {}
    // 根据章节id，查询书id
    let allResult = await this.getAllCategoriesWidthContent(bid)
    
    if(allResult.code === 0 ){
      let categoryArr = allResult.data
      let index = categoryArr.findIndex(item =>{
        return item.id === cid
      })
      res.code = 0
      if(index === -1){
        res.msg = '章节不存在'
        res.data = null
      }else {
        res.data = {
          pre : index > 0 ? categoryArr[index - 1] : null,
          cur : categoryArr[index],
          next: categoryArr[index + 1] || null
        }
      }
    }else{
      res.code = -1
      res.msg = '获取章节失败'
      res.date = null
    }
    return res
  }
  // 添加章节
  async addCategory(data){
    let res = {}
    let bid = data.bid
    // 查询书籍表中是否有该bid
    let book = await this.app.mysql.get('book',{id:bid})
    let uId = uuidv4()
    data.id = uId
    if (book) {
      data.bName = book.name
      let result = await this.app.mysql.insert('category',data)
      if(result.affectedRows === 1){
        res.code = 0
        res.msg = '插入章节成功'
      }else{
        res.code = -1
        res.msg = '插入章节失败'
      }
    }else{
      res.code = -1
      res.msg = '书籍id不存在'
    }
    return res
  }
  // 一次向插入一本书的所有章节
  async addAllCategoryByOneTime(categoryList) {
    // console.log('addAllCategoryByOneTime categoryList.length:',categoryList.length);
    let res = {}
    const conn = await this.app.mysql.beginTransaction();
    try {
      for (let category of categoryList) {
        await conn.insert('category',category)
      }
      // let insertCategoryFn = categoryList.map(async (category) => {
      //   await conn.insert('category',category)
      // })
      // // console.log('insertCategoryFn.length:',insertCategoryFn.length);
      // // console.log('insertCategoryFn[1]:',insertCategoryFn[1]);
      // await Promise.all(insertCategoryFn)
      // console.log('insertResults:',insertResults.length)
      // console.log('insertResults:', insertResults[0])
      await conn.commit()
      res.code = 0
      res.msg = '插入章节成功'
    } catch (error) {
      this.ctx.logger.error(error);
      res.code = -1
      res.msg = '插入章节失败'
      await conn.rollback()
    }
    return res
  }
  // 修改章节 
  async updateCategory(data){
    let res = {}
    let result = await this.app.mysql.update('category',data)
    if(result.affectedRows === 1){
      res.code = 0
      res.msg = '修改章节成功'
    }else{
      res.code = -1
      res.msg = '修改章节失败'
    }
    return res
  }
  // 删除章节
  async deleteCategory(id){
    let res = {}
    let category = await this.app.mysql.get('category',{id:id})
    if(category){
      let result = await this.app.mysql.delete('category',{id:id})  
      if(result.affectedRows === 1){
        res.code = 0
        res.msg = '删除章节成功'
      }else{
        res.code = -1
        res.msg = '删除章节失败'
      }
    }else{
      res.code = -1
      res.msg = '章节不存在'
    }
    return res
  }
  // 章节浏览量
  async addCategoryPvById(id) {
    const res = {}
    const preResult = await this.app.mysql.get('category', { id: id })
    if (preResult) {
      let pv = preResult.pv
      const result = await this.app.mysql.update('category', { id, pv: pv + 1 })
      if (result) {
        res.code = 0
        res.msg = '浏览量加1'
      } else {
        res.code = -1
        res.msg = '浏览量统计失败'
      }
    }else {
      res.code = -1
      res.msg = '浏览量统计失败'
    }
    
    return res
  }
}

module.exports = CategoryService